package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.CryptoUtil;
import com.zhongkai.StringStatic;
import com.zhongkai.app.service.AppRegLogService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.AppUser;
import com.zhongkai.model3.Chinaset;
import org.codehaus.jackson.map.ObjectMapper;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Service
@Transactional(rollbackFor = Exception.class)
public class AppRegLogServiceImpl implements AppRegLogService {


    @Autowired
    private IBaseDao iBaseDao;

    @Autowired
    private JedisClient jedisClient;


/*    @Autowired
    private JmsTemplate jmsTemplate;

    @Resource
    private Destination topicDestination;*/

/*    @Autowired
    private RocketMqProducer rocketMqProducer;*/

    /**
     * APP注册
     *
     * @param phone    手机号
     * @param password 密码
     * @param code     验证码
     */
    @Override
    public ZhongkaiResult user_registered(String phone, String password, String code
    ) throws IOException {

        if (StringUtils.isNullOrEmpty(phone)
                || StringUtils.isNullOrEmpty(password) || StringUtils.isNullOrEmpty(code)) {
            return ZhongkaiResult.build(400, "数据不完整,注册失败");
        }


        String jedcode = null;
        try {
            jedcode = jedisClient.get(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }


        if (!code.equals(jedcode)) {
            return ZhongkaiResult.build(400, "验证码错误");
        }
        AppUser appUser = (AppUser) iBaseDao.get("from AppUser tb where tb.appPhone='" + phone + "'");

        if (appUser != null) {

            return ZhongkaiResult.build(400, "您已注册请登录");
        }

/*
        AppRole appRole = (AppRole) iBaseDao.get("from AppRole su where su.roleName='普通用户'");


        if (appRole != null) {

            return ZhongkaiResult.build(400, "普通用户权限消失");
        }*/


        appUser = new AppUser();

        appUser.setAppUuid(TTHelp.generate());                              //设置用户uid

        appUser.setAppPhone(phone);                                         //用户手机号

        appUser.setAppName("中凯用户");                                           //用户姓名


        appUser.setAppImg("http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg");

/*        appUser.setAppVice(appRole.getRoleName());  //用户关系name 亲戚 朋友..........
        appUser.setAppViceId(appRole.getId()); //用户关系id*/

        //加密
        String pass = CryptoUtil.encode64(CryptoUtil.SALT, password);

        appUser.setAppPassword(pass); //设置加密后的密码


        long millis = new DateTime().getMillis(); //获取当前系统时间戳
        appUser.setAppTime(millis); //设置创建时间

        appUser.setAppRemove("1");  //1正常  2 删除
        //   appUser.setAppVice("2"); //是否为维修用户 1是 2否
        appUser.setAppVice("普通用户"); //设置权限
        appUser.setAppViceId(1); //设置权限 普通用户

        String generate = TTHelp.generate(); //生成Token
        appUser.setToken(StringStatic.TOKEN_ME + generate); //存入对象

        ObjectMapper mapper = new ObjectMapper();

        String appUserJson = mapper.writeValueAsString(appUser); //转成json

        try {
            jedisClient.set(StringStatic.TOKEN_ME + generate, appUserJson);  //加入缓存
            jedisClient.expire(StringStatic.TOKEN_ME + generate, 604800);//过期时间为一个星期

        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }


        iBaseDao.save(appUser);

        return ZhongkaiResult.ok(appUser);  //注册成功
    }

    /**
     * APP登录
     *
     * @param phone    手机号
     * @param password 密码
     * @param code     验证码
     * @param way      登录方式 1 密码登录 2验证码登录
     */
    @Override
    public ZhongkaiResult user_login(String phone, String password, String code, String way) throws Exception {

        if (StringUtils.isNullOrEmpty(phone) || StringUtils.isNullOrEmpty(way)) {
            return ZhongkaiResult.build(400, "数据不完整,登录失败");
        }

        AppUser appUser = (AppUser) iBaseDao.get("from AppUser tb where tb.appPhone='" + phone + "'");

        if (appUser == null) {

            return ZhongkaiResult.build(500, "用户不存在,登录失败");
        }


        if (way.equals("1")) {
            if (StringUtils.isNullOrEmpty(password)) {
                return ZhongkaiResult.build(500,"密码不能为空");
            }

            String appPassword = appUser.getAppPassword();

            String decontent = CryptoUtil.decode64(CryptoUtil.SALT, appPassword); //解密

            if (!password.equals(decontent)) {
                return ZhongkaiResult.build(500, "密码错误,登录失败");
            }


        } else if (way.equals("2")) {

            String jedcode = jedisClient.get(phone);


            if (!code.equals(jedcode)) {
                return ZhongkaiResult.build(400, "验证码错误");
            }


        } else {
            return ZhongkaiResult.build(400, "参数不合法");
        }

        try {
         //   String token = appUser.getToken();

            if (!StringUtils.isNullOrEmpty(appUser.getToken())){
             //   Long delete = jedisClient.delete(appUser.getToken());//生成新token之前删除及以前的
                jedisClient.expire(appUser.getToken(), 1);//过期时间为0

            }

            String generate = TTHelp.generate(); //生成Token
            appUser.setToken(StringStatic.TOKEN_ME + generate); //存入对象


            ObjectMapper mapper = new ObjectMapper();
            String chinasetJson = mapper.writeValueAsString(appUser); //转成json

            jedisClient.set(StringStatic.TOKEN_ME + generate, chinasetJson);  //加入缓存
            jedisClient.expire(StringStatic.TOKEN_ME + generate, 604800);//过期时间为一个星期

            iBaseDao.update(appUser);

            return ZhongkaiResult.ok(appUser);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }

        //  String pass = CryptoUtil.encode64(CryptoUtil.SALT, password);

        //String user_json = jedisClient.get(phone);
/*            if (user_json != null) {   //有缓存

                AUser user = new Gson().fromJson(user_json, AUser.class);
                //检查密码是否正确
                if (!pass.equals(user.getPassword())) {
                    return ZhongkaiResult.build(400, "密码错误,请重试");
                }else {


                    //重新设置缓存过期时间
                    jedisClient.set(user.getuPhone(), user_json);
                    jedisClient.expire(user.getuPhone(), 604800);//过期时间为一个星期
                    return ZhongkaiResult.build(200, "登录成功", user);
                }

            }*/


/*            Chinaset chinaset; //系统用户数据库

            //AUser aUser;  //没有缓存查询数据库
            chinaset = (Chinaset) iBaseDao.get("from Chinaset tb where tb.setPhone='" + phone + "'");
            //  jedisClient.get()
            if (chinaset == null) {
                return ZhongkaiResult.build(400, "该用户不存在,请注册");
            }


            //检查密码是否正确
            if (!pass.equals(chinaset.getPassWord())) {
                return ZhongkaiResult.build(400, "密码错误,请重试");
            } else {
                String user = new Gson().toJson(aUser);
                jedisClient.set(aUser.getuPhone(), user);
                jedisClient.expire(aUser.getuPhone(), 604800);//过期时间为一个星期

                System.out.println(user);

                //设定权限


                return ZhongkaiResult.build(200, "成功", aUser);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(400, "查询失败,请重试");
        }*/

        //   return null;
    }


    /**
     * APP根据手机号验证码修改密码
     *
     * @param phone    手机号
     * @param password 密码
     * @param code     验证码
     */
    @Override
    public ZhongkaiResult updatePassword(String phone, String password, String code) {
        if (StringUtils.isNullOrEmpty(phone) || StringUtils.isNullOrEmpty(password) || StringUtils.isNullOrEmpty(code)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        String jedcode = null;
        try {
            jedcode = jedisClient.get(phone);
        } catch (Exception e) {
            e.printStackTrace();

        }

        if (!code.equals(jedcode)) {
            return ZhongkaiResult.build(400, "验证码错误");
        }


        AppUser appUser = (AppUser) iBaseDao.get("from AppUser tb where tb.appPhone='" + phone + "'");

        if (appUser == null) {

            return ZhongkaiResult.build(400, "该用户不存在");
        }


        String pass = CryptoUtil.encode64(CryptoUtil.SALT, password);

        appUser.setAppPassword(pass); //设置加密后的密码

        iBaseDao.update(appUser);
        return ZhongkaiResult.ok();
    }


    /**
     * 更新缓存数据
     */
    @Override
    public void revision_user(String token) throws IOException {

        String userJson = null;
        try {
            userJson = jedisClient.get(token);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        Chinaset chinaset;
        ObjectMapper mapper = new ObjectMapper();

        chinaset = mapper.readValue(userJson, Chinaset.class);

        chinaset = (Chinaset) iBaseDao.get("from Chinaset tb where tb.uuid='" + chinaset.getUuid() + "'");

        chinaset.setToken(token);

        String chinasetJson = mapper.writeValueAsString(chinaset); //转成json
        try {
            jedisClient.set(token, chinasetJson);  //加入缓存
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        System.out.println(chinasetJson);
        System.out.println("更新成功");
/*        String ip = "";readValue
        AFacility aFacility = (AFacility) iBaseDao.get("from AFacility af where af.fUid='" + device_id + "'");

        if (aFacility == null) {
            return ZhongkaiResult.build(201, "设备不存在");
        } else {
            ip = aFacility.getfIpAddress();
            return ZhongkaiResult.ok(ip);
        }*/

    }


}
